<template>
    <el-form ref="actionform" :model="formData" label-width="80px" v-loading="showLoading">
		<el-form-item label="类型" verify prop="bannerType">
			<el-select v-model="formData.bannerType" placeholder="请选择类型" class="formItem" @change="handleTypeChange">
				<el-option
					v-for="item in typeList"
					:key="item.labelId"
					:label="item.labelText"
					:value="item.labelId">
				</el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="标题" verify prop="bannerTitle">
			<el-input class="formItem" v-model="formData.bannerTitle" placeholder="请输入标题"></el-input>
		</el-form-item>
		<el-form-item label="描述" prop="bannerDesc">
			<el-input
				class="formItem"
				type="textarea"
				:autosize="{ minRows: 2, maxRows: 4}"
				v-model="formData.bannerDesc"
				placeholder="请输入描述">
			</el-input>
		</el-form-item>
		<el-form-item label="排序" verify prop="bannerSort">
			<el-input-number v-model="formData.bannerSort" class="formItem" :min="1" label="排序" />
		</el-form-item>
		
		<el-form-item :label="'关联'+ typeName" verify prop="bannerContentUid" v-if="typeName">
			<el-select
				filterable
				v-model="formData.bannerContentUid"
				class="formItem"
				:placeholder="'请选择关联' + typeName">
				<el-option
					v-for="item in relatedList"
					:key="item.labelId"
					:label="item.labelText"
					:value="item.labelId">
				</el-option>
				<el-pagination
					@current-change="handleCurChange"
					:current-page="page"
					background
					hide-on-single-page
					layout="total, prev, pager, next, jumper"
					:total="count">
				</el-pagination>
			</el-select>
		</el-form-item>

		<el-form-item label="轮播图" prop="bannerImageUrl" verify>
			<el-upload
				:action="uploadUrl"
				:data="access_token"
				:show-file-list="false"
				:before-upload="$util.beforeUpload"
				:on-success="uploadImageSuccess">
				<el-image :src="formData.bannerImageUrl" class="avatar" v-if="formData.bannerImageUrl" />
				<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				<el-input class="inputs none imgArea" v-model="formData.bannerImageUrl" />
			</el-upload>
		</el-form-item>
		<el-form-item  label="定时上线" prop="timeInterval">
			<el-date-picker
				class="formItem"
				v-model="formData.timeInterval"
				type="datetime"
				value-format="yyyy-MM-dd HH:mm:ss"
				placeholder="选择日期时间 (可选)">
			</el-date-picker>
		</el-form-item>
	
		<el-form-item style="margin-bottom: 0">
			<p class="flex-center margin_top_30">
				<el-button type="primary" @click="handlePost">确  认</el-button>
				<el-button @click="closeDialog">取  消</el-button>
			</p>
		</el-form-item>
	</el-form>
</template>

<script>
    import {
		addBanner,
		editBanner,
 		getGoodslist,
		campaignsList,
		blessingList
	} from "@/api/table";

    export default {
        name: "BANNER_ACTION",
        components: { },
        props: {
            infoData: {
            	type: Object,
                default() {
					return {}
				}
			},
			typeList: {
				type: Array,
                default() {
					return []
				}
			}
		},
		watch: {},
        data() {
            return {
				formData: {},
				page: 1,
				count: 0,
				typeName: '',
				relatedList: [],
				showLoading: false,  
				access_token: {
                    access_token: this.$store.getters.token
                },
				uploadUrl: process.env[this.$base] + "/medias/image/upload",
            }
        },
      	methods: {
			async updateData() {
				this.formData = {...this.infoData};
				const { bannerType, } = this.formData;
				this.typeName = this.getTypeName(bannerType);
				await this.getData(bannerType)
			},

			// 获取商品数据
            getGoodslistData() {
                getGoodslist({
                    status: '1',
                    page: this.page - 1,
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        const { productList, count } = res.data.data;
						this.count = count;
						this.relatedList = this.filterData(productList)
                    }
                });
            },
            // 获取活动数据
            getCampaignsList() {
                campaignsList({
                    campaignState: 3,
                    page: this.page - 1,
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
						const { campaignsList, count } = res.data.data;
						this.count = count;
						this.relatedList = this.filterData(campaignsList)
                    }
				});
			},
			
			// 获取资源数据
            getBlessingList() {
                blessingList({
                    resourceState: 2,
                    page: this.page - 1,
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
						const { data, count } = res.data.data;
						this.count = count;
						this.relatedList = this.filterData(data)
                    }
				});
            },

			// 获取labelText, labelId
			getRelateInfo(info) {
				let labelText = '';
				let labelId = '';
				switch (this.formData.bannerType) {
					// 活动
					case 1: return {
						labelText: info.campaignSubject,
						labelId: info.campaignUid
					};
					// 资源
					case 2: return {
						labelText: info.resourceName,
						labelId: info.resourceUid
					};
					// 商品
					case 5: return {
						labelText: info.productName,
						labelId: info.productUid
					};
					// case 3: return {
					// 	labelText: info.campaignName,
					// 	labelId: info.campaignUid
					// };
					// case 4: return {
					// 	labelText: info.productName,
					// 	labelId: info.productUid
					// };
					default: return {};
				}
			},

			// 处理数据
			filterData(data) {
				let afterData = [];
				data.map(item => {
					let { labelText, labelId } = this.getRelateInfo(item);
					return afterData.push({
						...item,
						labelText,
						labelId
					})
				});
				return afterData
			},

			// 类型change
			async handleTypeChange(e) {
				this.page = 1;
				this.typeName = this.getTypeName(e);
				this.$set(this.formData, 'bannerContentUid', '')
				await this.getData(e);
			},

			async getData(key) {
				switch (key) {
                    case 1:
						// 活动列表
                        await this.getCampaignsList()
                        break;
                    case 2:
						// 资源列表
                        await this.getBlessingList()
                        break;
                    case 3:
                        // await this.getGoodslistData();
                        break;
                    case 4:
                        // await this.getGoodslistData();
                        break;
                    case 5:
                        // 商品列表
                        await this.getGoodslistData();
                        break
                    default:
                        break;
				}
			},

			// 分页数据
			handleCurChange(val) {
				this.page = val;
                this.getData(this.formData.bannerType);
			},

			// 获取类型
            getTypeName(labelId) {
                const info = this.typeList.find(item => item.labelId === labelId) || {}
                return info.labelText || ''
            },

			// banner图
			uploadImageSuccess(response, file, fileList) {
				if (response.code == "200") {
					const { fileUrl, fileUid } = response.data;
					this.$set(this.formData, 'bannerImageUrl', fileUrl);
				}
			},

			// 确认
			handlePost() {
				this.$refs.actionform.validate(valid => {
					if (valid) {
						this.showLoading = true;
						// 编辑
						if (this.formData.bannerUid) {
							const {
								bannerUid,
								bannerType,
								bannerContentUid,
								bannerSort,
								bannerTitle,
								timeInterval,
								bannerImageUrl
							} = this.formData;

							editBanner({
								bannerUid,
								bannerType,
								bannerContentUid,
								bannerSort,
								bannerTitle,
								timeInterval,
								bannerImageUrl
							}).then(res => {
								if (res.data.isSuccessful !== "Y") {
									this.$message.error(res.data.message);
									return
								}
								this.$message({
									message: "编辑成功！",
									type: "success"
								});
								setTimeout(() => {
									this.closeDialog(true);
								}, 0);
							}).finally(() => {
								this.showLoading = false;
							});
							return
						}

						// 新增
						addBanner(this.formData).then(res => {
							if (res.data.isSuccessful !== "Y") {
								this.$message.error(res.data.message);
								return
							}
							this.$message({
								message: "新增成功！",
								type: "success"
							});
							setTimeout(() => {
								this.closeDialog(true);
							}, 0);
						}).finally(() => {
							this.showLoading = false;
						});
					}
				})
			},

			closeDialog(refresh = false, type = ''){
				this.formData = {};
				this.$emit('func', {
					action: false,
					refresh,
					type
				})
			}
      	},
  	}
</script>
<style lang="scss" scoped>
	.formItem {
		width: 360px;
    }
</style>

